package com.powernode.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.reggie.common.CustomException;
import com.powernode.reggie.entity.Category;
import com.powernode.reggie.entity.Dish;
import com.powernode.reggie.entity.Setmeal;
import com.powernode.reggie.mapper.CategoryMapper;
import com.powernode.reggie.service.CategoryService;
import com.powernode.reggie.service.DishService;
import com.powernode.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @description:
 * @author: www
 * @time: 2023/3/8 16:05
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;
    /**
     * 根据id删除分类，但是删除前需要判断是否关联菜品或套餐；（自己定义不用继承）
     * @param id
     */
    @Override
    public void remove(Long id) {
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据分类id进行查询
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        int count1 = dishService.count(dishLambdaQueryWrapper);//查询具有这个id的dish数据条数

        // 查询当前分类是否关联菜品，如果关联，抛出一个异常
        if(count1 > 0){
            //已经关联菜品，抛出一个异常
            throw new CustomException("当前分类下关联菜品，无法删除");
        }

        //查询当前分类是否关联套餐，如果关联，抛出一个异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(setmealLambdaQueryWrapper);
        if(count2 > 0){
            //已经关联套餐，抛出一个异常
            throw new CustomException("当前分类下关联套餐，无法删除");
        }

        //正常删除分类
        super.removeById(id);
    }
}
